var common = require('../../utils/common.js');
const app = getApp()
Page({
  data: {
    solitaire: [],
    solitaireId: '',
    item:[],
    logined: false,
    hasShop: false,
    fromapp: false,
    linkAppid: 'wx13e41a437b8a1d2e',
    path:'',
    url:'',
    options:'',
    showShareTip: false,
    isloaded: false,
    fromUserId: '',
    imgbgsrc: '',
    loading: false,
    shareimg1: '',
    fromShopkeeper: false,
    statusBarHeight: app.globalData.statusBarHeight,
  },
  onLoad: function (option) {
    console.log(option)
    console.log(app.globalData.path)
    console.log(this.data.url, this.data.options)
    if (option){
      this.setData({
        solitaireId: option.solitaireId,
        fromUserId: option.userId
      })
    }
    if (wx.getStorageSync('sessionId')) {
      this.setData({
        logined: true,
        sessionId: wx.getStorageSync('sessionId')
      })
      this.getSolitaireData()
      this.getShopData()
    }else{
      // this.loginTip()
      this.setData({
        logined: true,
      })
      this.getSolitaireData()
    }
  },
  onShow(res){
    wx.hideHomeButton()
    console.log(res)
    // this.getpic()
  },
  onShareAppMessage: function () {
    console.log('/pages/shareSolitaireD/shareSolitaireD?solitaireId=' + this.data.solitaireId + '&userId=' + this.data.fromUserId)
    return {
      title: app.globalData.userInfo.nickname + '邀请你参加接龙',
      imageUrl: this.data.shareimg1,
      path: '/pages/shareSolitaireD/shareSolitaireD?solitaireId=' + this.data.solitaireId + '&userId=' + this.data.fromUserId
      
    }
  },
  getSolitaireData() {
    wx.showLoading({
      title: '加载中',
    })
    const that = this
    common.post({
      url: '/app/v2/skusolitaire/info', data: { solitaireId: this.data.solitaireId }
    })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == 0) {
          if (res.data.data.sku.images){
            var imgstr = JSON.parse(res.data.data.sku.images)
            console.log(imgstr)
          }
          that.setData({
            solitaire: res.data.data,
            item: res.data.data.sku,
            isloaded: true,
            itemPic: imgstr,
            actEndTime: res.data.data.endTime
          })
          that.countDown()
          setTimeout(function () {
            that.setData({
              loaded: true
            })
            wx.hideLoading()
          }, 2000)
          wx.setNavigationBarTitle({
            title: that.data.solitaire.title
          })
          console.log(that.data.item)
          that.getitemlink()
          console.log(that.data.solitaire)
          that.getpic()
        } else if (res.data.code == -9998) {
          wx.hideLoading()
          that.loginTip()
        } else {
          console.log(res)
        }
      }).catch((res) => {
        console.log(res)
      })
  },
  loginTip() {
    const that = this
    wx.showModal({
      title: '提示',
      content: '你需要登录，才能享受优惠',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          that.runLogin()
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  runLogin() {
    const that = this
    let res = app.login(app.globalData.thisshareTicket)
    let promise = new Promise((resolve, reject) => {
      let timer = setInterval(() => {
        // console.log(app.globalData.sessionId,app.globalData.userId)
        if (that.data.sessionId && app.globalData.userId) {
          clearInterval(timer);
          resolve(app.globalData);
          console.log('登录')
          that.getSolitaireData()
          that.getShopData()
        } else {
          //todo 信息构建中
        }
      }, 250);
    });
  },
  getitemlink() {
    const that = this
    if (this.data.sessionId) {
      that.linkData(1)
    } else {
      
    }
  },
  async linkData(e) {
    if (e == 2) {
      console.log(2)
      await app.login(app.globalData.thisshareTicket)
      // await this.link()
    } else {
      console.log(1)
      this.link()
    }

  },
  async link() {
    const that = this
    var couponId
    if (this.data.item.coupons) {
      couponId = this.data.item.coupons[0].couponId
    } else {
      couponId = ''
    }
    var fromUserId =''
    if(this.data.fromUserId !== undefined){
      fromUserId = this.data.fromUserId
    }else{
      fromUserId = ''
    }
    common.post({
      url: '/app/goods/getLink', 
      data: {
        skuId: that.data.item.skuId,
        couponId: couponId,
        sessionId: this.data.sessionId,
        pUserId: fromUserId
      }
    })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == 0) {
          that.setData({
            link: res.data.link,
            logined: true
          });
          var link = encodeURIComponent(that.data.link)
          console.log(that.data.item.sku)
          var path = '/pages/product/product?wareId=' + that.data.item.sku + '&spreadUrl=' + link + '&customerinfo=' + that.data.customerinfo
          console.log(path)
          that.setData({
            item: app.globalData.item,
            path: path
          });
        } else {
          app.login()
        }
      }).catch((res) => {
        console.log(res)
      })
  },
  getShopData(){
    const that = this
    common.post({
      url: '/app/v2/shop/shopInfo', data: { sessionId: this.data.sessionId, userId: this.data.fromUserId }
    })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == "0") {
          console.log(res.data.data.status)
          if (res.data.data.status == 2){
            that.setData({
              hasShop: true
            })
            
          }
        }
      }).catch((res) => {
        console.log(res)
        app.timeOutTip()
      })
  },
  buybtnlink: function () {
    const that = this
    console.log(this.data.sessionId)
    if (this.data.sessionId) {
      wx.navigateToMiniProgram({
        appId: this.data.linkAppid,
        path: this.data.path,
        extraData: {
          foo: 'bar'
        },
        success(res) {
          console.log(res)
          // 打开成功
          setTimeout(() => {
            that.shareSolitaireTip()
            that.joinSolitaire()
          }, 1000);
          
        }
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '你需要登录，才能享受优惠',
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定')
            app.login(app.globalData.thisshareTicket)
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }

  },
  toIndex() {
    wx.switchTab({
      url: '/pages/itemlist/itemlist',
      success: function (res) {
        console.log('toItemlist')
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  toUsercenter() {
    wx.switchTab({
      url: '/pages/usercenter/usercenter',
      success: function (res) {
        app.globalData.fromShopkeeper = true
        console.log('toUsercenter')
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  toIndex(){
    wx.switchTab({
      url: '/pages/itemlist/itemlist',
      success: function (res) {
        app.globalData.fromShopkeeper = true
        console.log('toItemlist')
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  toStore(){
    console.log(this.data.userId)
    wx.navigateTo({
      url: '/pages/shareShop/shareShop?userId=' + this.data.fromUserId,
      success: function (res) {
        console.log('toShareShop')
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  shareSolitaireTip(){
    this.setData({
      showShareTip: true
    })
  },
  clickShareBtn(){
    this.setData({
      showShareTip: false
    })
    this.getSolitaireData()
    console.log(app.globalData.path)
  },
  joinSolitaire(){
    const that = this
    common.post({
      url: '/app/v2/skusolitaire/join', data: { sessionId: this.data.sessionId, solitaireId: this.data.solitaireId }
    })
      .then((res) => {
        console.log(res.data)
      }).catch((res) => {
        console.log(res)
        app.timeOutTip()
      })
  },
  getpic() {
    wx.showLoading({
      title: '接龙生成中...',
    })
    const that = this
    var imgbgsrc = this.data.solitaire.sku.image
    wx.getImageInfo({
      src: imgbgsrc,
      success: function (res) {
        that.setData({
          imgbgsrc: res.path
        })
        console.log(that.data.imgbgsrc)
      }
    })
    let promise = new Promise((resolve, reject) => {
      let timer = setInterval(() => {
        // console.log(app.globalData.sessionId,app.globalData.userId)
        if (that.data.imgbgsrc !== '') {
          clearInterval(timer);
          resolve(that.data);
          that.getSharePic()
        } else {

        }
      }, 250);
    });
  },
  getSharePic() {
    const that = this
    var str1 = this.data.solitaire.title
    var str2 = '我要接龙'
    const sharepic = wx.createCanvasContext('myCanvas')
    console.log(that.data.imgbgsrc)
    sharepic.drawImage(that.data.imgbgsrc, 0, -40, 500, 500)
    sharepic.setFillStyle('#fff')
    sharepic.fillRect(0, 0, 500, 40)
    sharepic.setFillStyle('#fff')
    sharepic.fillRect(0, 320, 500, 80)
    sharepic.setTextAlign('left')
    sharepic.setFontSize(20)
    sharepic.setFillStyle('#333')
    sharepic.fillText(str1, 20, 25)
    sharepic.arc(50, 360, 30, 0, Math.PI * 2, false);
    sharepic.setFillStyle('#f95050')
    sharepic.fill()
    sharepic.arc(450, 360, 30, 0, Math.PI * 2, false);
    sharepic.setFillStyle('#f95050')
    sharepic.fill()
    sharepic.setFillStyle('#f95050')
    sharepic.fillRect(50, 330, 400, 60)
    sharepic.setFontSize(26)
    sharepic.setTextAlign('center')
    sharepic.setFillStyle('#fff')
    sharepic.fillText(str2, 250, 370)
    sharepic.draw(false, function (e) {
      console.log(e)
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: 500,
        height: 400,
        destWidth: 500,
        destHeight: 400,
        canvasId: 'myCanvas',
        success: function (res) {
          console.log(res.tempFilePath)
          that.setData({
            shareimg1: res.tempFilePath,
            imgShow: true,
            loading: true,
          });
          wx.hideLoading()
        },
        fail(res) {
          console.log(res)
        }
      })
    })
  },
  countDown() {//倒计时函数
    // 获取当前时间，同时得到活动结束时间数组
    console.log('获取结束时间',this.data.solitaire.endTime)
    var thisendTime = this.data.solitaire.endTime
    let newT = thisendTime.replace(/-/g, '/');
    let date = new Date(newT );
    console.log(date);
    let newTime = new Date().getTime();
    let endTimeList = new Date(date).getTime();
    let countDownArr = [];

    // 对结束时间进行处理渲染到页面
    // let endTime = new Date(endTimeList).getTime();
    let endTime = endTimeList;
    // console.log(endTime, newTime)
    let obj = null;
    // 如果活动未结束，对时间进行处理
    console.log('结束时间：', endTime)
    console.log('当前时间', newTime)
    if (endTime - newTime > 0) {
      let time = (endTime - newTime) / 1000;
      // 获取天、时、分、秒
      // let day = parseInt(time / (60 * 60 * 24));
      let hou = parseInt(time % (60 * 60 * 48) / 3600);
      let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
      let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
      obj = {
        // day: this.timeFormat(day),
        hou: this.timeFormat(hou),
        min: this.timeFormat(min),
        sec: this.timeFormat(sec)
      }
      setTimeout(this.countDown, 1000);
    } else {//活动已结束，全部设置为'00'
      obj = {
        // day: '00',
        hou: '00',
        min: '00',
        sec: '00'
      }
      wx.showModal({
        title: '提示',
        content: '活动已结束',
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
    // 渲染，然后每隔一秒执行一次倒计时函数
    this.setData({ 
      countDownList: obj
    })
    // console.log(this.data.countDownList)
  },
  timeFormat(param) {//小于10的格式化函数
    return param < 10 ? '0' + param : param;
  },
  toShopBtn(){
    wx.navigateTo({
      url: '/pages/shareShop/shareShop?userId=' + this.data.fromUserId,
      success: function (res) {
        console.log('toInitiateJl')
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  
})